<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--目录数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container mb8">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['company:knowledge:type:add']">新增</el-button>
        </div>
        <div class="head-container">
          <el-table v-if="refreshTable" v-loading="loading" border :data="deptList" row-key="klgTypeId"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column prop="typeName" label="目录名称" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['company:knowledge:type:add']"></el-button>
                <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                  v-hasPermi="['company:knowledge:type:add']"></el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['company:knowledge:type:remove']"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain v-if="isShowAdd" icon="el-icon-plus" size="mini" @click="handleAddDoc"
              v-hasPermi="['company:knowledge:add']">新增</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDeleteDoc"
              v-hasPermi="['company:knowledge:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              >批量转移</el-button
            >
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column :show-overflow-tooltip="true" label="ID" align="center" prop="klgDocId" />
          <el-table-column :show-overflow-tooltip="true" label="标题" align="center" prop="docTitle">
            <template slot-scope="scope">
              <el-link @click="handleDetail(scope.row.klgDocId)" type="primary">{{ scope.row.docTitle }}</el-link>
            </template>
          </el-table-column>

          <el-table-column :show-overflow-tooltip="true" label="分类" align="center" prop="klgTypePath" />
          <el-table-column :show-overflow-tooltip="true" label="文档类型" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_klg_type" :value="scope.row.docType" />
            </template>
          </el-table-column>

          <el-table-column :show-overflow-tooltip="true" label="由谁添加" align="center" prop="createByName" />
          <el-table-column width="200" :show-overflow-tooltip="true" label="添加时间" align="center" prop="createTime" />
          <el-table-column label="是否置顶" align="center" width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.isTop" 
                @change="handleIsTop(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['company:knowledge:info']"
                @click="handleDetail(scope.row.klgDocId)">详情</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateDoc(scope.row)"
                v-hasPermi="['company:knowledge:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteDoc(scope.row)"
                v-hasPermi="['company:knowledge:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改目录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级目录" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" :show-count="true"
                placeholder="选择上级目录" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="目录名称" prop="typeName">
              <el-input v-model="form.typeName" placeholder="请输入目录名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改目录对话框 -->
    <el-dialog :title="titleDoc" :visible.sync="openDoc" width="800px" append-to-body>
      <el-form ref="formDoc" :model="formDoc" :rules="rulesDoc" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="目录" prop="klgTypeId">
              <treeselect v-model="formDoc.klgTypeId" :options="deptOptions" :normalizer="normalizer" :show-count="true"
                placeholder="选择目录" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文档标题" prop="docTitle">
              <el-input v-model="formDoc.docTitle" placeholder="请输入文档标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="简介" prop="concise">
              <el-input v-model="formDoc.concise" placeholder="请输入简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文档类型" prop="docType">
              <el-select @change="changeSelect" v-model="formDoc.docType" placeholder="请选择文档类型" clearable>
                <el-option v-for="dict in dict.type.sys_klg_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formDoc.docType">
          <el-col :span="24">
            <el-form-item label="文档内容" prop="content">
              <el-input v-if="formDoc.docType == 3" v-model="formDoc.content" placeholder="请输入链接（格式http://或https://开头）" />
              <FileUpload v-if="formDoc.docType == 2" v-model="formDoc.content"></FileUpload>
              <!-- <tinymce
                v-if="formDoc.docType == 1"
                v-model="formDoc.content"
                placeholder="请输入文档内容"
                :height="500"
              ></tinymce> -->
              <editor v-if="formDoc.docType == 1" placeholder="请输入文档内容" v-model="formDoc.content" :min-height="500" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDoc">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <detail :detailOPen.sync="detailOPen" :rowDetail="rowDetail" @cancel="cancel"></detail>
  </div>
</template>

<script>
import {
  docList,
  docDel,
  docEdit,
  docAdd,
  docInfo,
  setTop
} from "@/api/company/doc.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { typeList, typeDel, typeEdit, typeAdd } from "@/api/company/type.js";
import detail from "./detail.vue";

export default {
  name: "Knowledge",
  dicts: ["sys_klg_type"],
  components: { Treeselect, detail },
  data() {
    return {
      deptList: [],
      refreshTable: true,
      isExpandAll: true,

      isShowAdd: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "哈哈哈",
      // 目录树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      openDoc: false,
      titleDoc: '',
      // 日期范围
      roleOptions: [],
      // 表单参数
      form: {},
      formDoc: { content: "" },
      rowDetail: {},
      detailOPen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `目录`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级目录不能为空", trigger: "blur" },
        ],
        typeName: [
          { required: true, message: "目录名称不能为空", trigger: "blur" },
        ],
      },
      rulesDoc: {
        concise: [{ required: true, message: "简介不能为空", trigger: "blur" }],

        klgTypeId: [
          { required: true, message: "目录不能为空", trigger: "blur" },
        ],
        docTitle: [
          { required: true, message: "文档标题不能为空", trigger: "blur" },
        ],
        docType: [
          { required: true, message: "文档类型不能为空", trigger: "change" },
        ],
        content: [
          { required: true, message: "文档内容不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选目录树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    if (this.$route.query.isadd) {
      this.isShowAdd = false;
    }
    if (this.$route.query.id) {
      this.handleDetail(this.$route.query.id);
    }
    if (this.$route.query.add) {
      this.handleAdd();
    }
    this.getList();
    this.getdepList();
  },
  methods: {
    handleIsTop(row) {
      console.log();
      let text = row.topTime ? "取消置顶" : "置顶";
      let type = row.topTime ? 2 : 1;

      this.$modal
        .confirm('确认要"' + text + '""' + row.concise + '"文档吗？')
        .then(function () {
          return setTop(row.klgDocId, type);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        })
        .catch(function () {
          row.isTop = type ? true : false;
        });
    },
    handleDetail(row) {
      this.detailOPen = true;

      docInfo(row).then((res) => {
        this.rowDetail = res.data;
      });
      // this.rowDetail = JSON.parse(JSON.stringify(row));
    },
    changeSelect() {
      this.formDoc.content = "";
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.klgTypeId,
        label: node.typeName,
        children: node.children,
      };
    },
    getdepList() {
      this.loading = true;
      typeList().then((response) => {
        this.loading = false;

        this.deptList = this.handleTree(response.data, "klgTypeId");
      });
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      docList(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          // response.rows.forEach(element => {
          //   element.type = element.topTime ? 2 : 1
          //   console.log(element.type);
          // });
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log(this.userList);
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openDoc = false;
      this.detailOPen = false;

      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.formDoc = { content: "" };
      this.resetForm("formDoc");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.klgDocId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleAddDoc() {
      this.reset();
      typeList().then((response) => {
        this.deptOptions = [];
        // const menu = { klgTypeId: 0, typeName: "主类目", children: [] };
        // menu.children = this.handleTree(response.data, "klgTypeId");
        this.deptOptions = this.handleTree(response.data, "klgTypeId");
        this.openDoc = true;
        this.titleDoc = "添加文档";
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      typeList().then((response) => {
        if (row != null && row.klgTypeId) {
          this.form.parentId = row.klgTypeId;
        } else {
          this.form.parentId = 0;
        }
        this.deptOptions = [];
        const menu = { klgTypeId: 0, typeName: "主类目", children: [] };
        menu.children = this.handleTree(response.data, "klgTypeId");
        this.deptOptions.push(menu);
        this.open = true;
        this.title = "添加目录";
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      typeList().then((response) => {
        this.deptOptions = [];
        const menu = { klgTypeId: 0, typeName: "主类目", children: [] };
        menu.children = this.handleTree(response.data, "klgTypeId");
        this.deptOptions.push(menu);
        this.form = JSON.parse(JSON.stringify(row));
        this.title = "修改目录";
      });
    },
    handleUpdateDoc(row) {
      this.reset();
      this.openDoc = true;
      typeList().then((response) => {
        this.deptOptions = [];
        const menu = { klgTypeId: 0, typeName: "主类目", children: [] };
        menu.children = this.handleTree(response.data, "klgTypeId");
        this.deptOptions.push(menu);
        this.formDoc = JSON.parse(JSON.stringify(row));
        this.titleDoc = "修改文档";
      });
    },
    submitFormDoc: function () {
      this.$refs["formDoc"].validate((valid) => {
        if (valid) {
          if (this.formDoc.klgDocId != undefined) {
            docEdit(this.formDoc).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.openDoc = false;
              this.getList();
            });
          } else {
            docAdd(this.formDoc).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.openDoc = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.klgTypeId != undefined) {
            typeEdit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getdepList();
            });
          } else {
            typeAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getdepList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除目录为"' + row.typeName + '"的数据项？')
        .then(function () {
          return typeDel(row.klgTypeId);
        })
        .then(() => {
          this.getdepList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleDeleteDoc(row) {
      const configIds = row.klgDocId || this.ids;
      let name = this.checkRow(
        configIds,
        this.userList,
        "klgDocId",
        "DELETE",
        "docTitle"
      );
      this.$modal
        .confirm('是否确认删除标题为"' + name + '"的数据项？')
        .then(function () {
          return docDel(configIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  img {
    width: 100%;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
